package com.zhiyun;

import com.zhiyun.vo.AppData;
import com.zhiyun.vo.Result;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zc
 * @Date 2025/4/28 上午11:29
 */
public class ServerMain {
    private static ExecutorService pool = Executors.newCachedThreadPool();
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(AppData.ServerPort);
            System.out.println("服务器启动成功");
            while (true) {
                Socket socket = serverSocket.accept();
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                            String interfaceName = objectInputStream.readUTF();
                            String methodName = objectInputStream.readUTF();
                            Class[] parameterTypes = (Class[]) objectInputStream.readObject();
                            Object[] args = (Object[]) objectInputStream.readObject();
                            InputStream inputStream = ServerMain.class.getClassLoader().getResourceAsStream("service.properties");
                            Properties properties = new Properties();
                            properties.load(inputStream);
                            Class<?> clazz = Class.forName(properties.getProperty(interfaceName));
                            Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
                            declaredConstructor.setAccessible(true);
                            Object object = declaredConstructor.newInstance();
                            Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
                            method.setAccessible(true);
                            Result res = (Result) method.invoke(object, args);
                            objectOutputStream.writeObject(res);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
